package com.common.account.granter;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义token返回内容
 *
 * @author wangguochao
 */
public class MyTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        try {
            if (oAuth2Authentication != null) {
                User user = (User) ((Authentication) oAuth2Authentication).getDetails();
                if (user == null) {
                    user = (User) oAuth2Authentication.getUserAuthentication().getPrincipal();
                }
                Map<String, Object> map = new LinkedHashMap<>();
                token.setAdditionalInformation(map);
            }
            return oAuth2AccessToken;
        } catch (Exception e) {
            return oAuth2AccessToken;
        }
    }
}
